import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.jar.JarFile;
import java.util.jar.Pack200;
import java.util.jar.Pack200.Packer;
import java.util.zip.GZIPOutputStream;


@SuppressWarnings("rawtypes")
public class SitePacker {

	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws IOException {
		Packer packer = Pack200.newPacker();

		// Initialize the state by setting the desired properties
		Map p = packer.properties();
		// take more time choosing codings for better compression
		p.put(Packer.EFFORT, "9");  // default is "5"
		// reorder files for better compression.
		p.put(Packer.KEEP_FILE_ORDER, Packer.TRUE);
		// smear modification times to a single value.
		p.put(Packer.MODIFICATION_TIME, Packer.KEEP);
		// transmitting a single request to use "store" mode.
		p.put(Packer.DEFLATE_HINT, Packer.FALSE);
		// throw an error if an attribute is unrecognized
		p.put(Packer.UNKNOWN_ATTRIBUTE, Packer.ERROR);

		packJar(packer, args[0]);
	}
	
	public static File packJar(Packer packer, String jarPath) throws IOException {
		File output = new File(jarPath + ".pack.gz");
		System.out.println("Packing " + output);
		JarFile jarFile = new JarFile(jarPath);
		OutputStream fos = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(output)));
		// Call the packer
		packer.pack(jarFile, fos);
		jarFile.close();
		fos.close();
		return output;
	}
	
}
